﻿using Glorysoft.Auto.Xfw;
using Glorysoft.Auto.Xfw.Contract;
using Glorysoft.Auto.Xfw.Entities;
using Glorysoft.EAP.Core;
using Glorysoft.EAP.Core.Entities;
using Glorysoft.EAP.EAPClient.Common;
using Glorysoft.EAP.EAPClient.Model;
using Glorysoft.EAP.EAPClient.View;
using Glorysoft.EAP.EAPClient.ViewModel;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // 如果你使用Newtonsoft.Json库来序列化JSON  
using System.Linq;
using static Glorysoft.EAP.EAPClient.Model.SlotMap;
using static Glorysoft.EAP.EAPClient.ViewModel.SelectWaferViewModel;

namespace Glorysoft.EAP.EAPClient
{
    public class EAPClient
    {
       
        private const string MsgNameSendConnect = "SendConnect";
        private const string MsgNameSendRemoveLot = "SendRemoveLot";
        private const string MsgNameChangeLanguage = "ChangeLanguage";      
        private const string MsgNameTrackOutByUser = "TrackOutByUser";
        private const string MsgNameTrackOutByOCR = "TrackOutByOCR";
        private const string MsgNameLogin = "Login";
        private const string MsgNameGetCarrierLotInfo = "GetCarrierLotInfo";    
        private const string MsgNameStartProgram = "StartProcess";
        private const string MsgNameSendStopProcess = "StopProcess";
        private const string MsgNameSelectWaferID = "SelectWaferID";
        private const string MsgNameClearAlarm = "ClearAlarm";
        private const string HeartBeat = "HeartBeat";

        private IMqContext context;
        private string requestClient=Dict.Current.EAPName;
        protected readonly IConfiguration Config;
       

        public EAPClient()
        {
           // requestClient = "EAP";
            Config = XfwContext.Configuration as IConfiguration;
        }
        public Model.RunService ClientInfo
        {
            get
            {
                return Model.RunService.Current;
            }
        }   
        public Return SendConnect(ConnectModel _model)
        {
            var retMsg = new Return();
            try
            {
                EAPClient cq = new EAPClient();
               // requestClient = cq.Config.GetSection("RequestClient").Get<string>();
                var request = new Request() { Header = XfwUtils.CreateHeader(MsgNameSendConnect, requestClient) };
                request.Body.AddString(CItems.EqpID, _model.EQPID);
                var strText = XfwUtils.Serialization(request.GetSerializationObject());
                context = XfwContext.GetMqContextByEAP(requestClient);
                var res = context.Request(strText);
                if (res != null)
                {
                    retMsg = res.GetReturnObject();
                }
                XfwContext.EapLogger.Information($"EAPClient.SendConnect() Execute. ReturnCode: {retMsg.ReturnCode}, ReturnMessage: {retMsg.ReturnMessage}");
            }
            catch (Exception ex)
            {
                retMsg.SetReturnNG(ex.Message);
                XfwContext.EapLogger.Error(ex, $"EAPClient.SendConnect() Execute Error.");
            }
            return retMsg;
        }
       
        /// <summary>
        /// 在客户端手动删除lot信息
        /// </summary>
        /// <param name="eqpId"></param>
        /// <param name="portId"></param>
        /// <returns></returns>
        public Return SendRemoveLot(string eqpId, string portId, string userid)
        {
            EAPClient cq = new EAPClient();
           // requestClient = cq.Config.GetSection("RequestClient").Get<string>();
            var retMsg = new Return();
            try
            {
                if (EQPStatus.MagazineList.Contains(EQPStatus.currenteqpid))
                    MainWindow.magazineDic.Remove(EQPStatus.currenteqpid);
                if (EQPStatus.TrayList.Contains(EQPStatus.currenteqpid))
                {
                    MainWindow.trayDic.Remove(EQPStatus.currenteqpid);
                }
                if (EQPStatus.TrayTransferList.Contains(EQPStatus.currenteqpid))
                {
                    MainWindow.traytransferDic.Remove(EQPStatus.currenteqpid);
                }
                var request = new Request() { Header = XfwUtils.CreateHeader(MsgNameSendRemoveLot, requestClient) };
                request.Body.AddString(CItems.EqpID, eqpId);
                request.Body.AddString(CItems.PortID, portId);
                request.Body.AddString(CItems.UserID, userid);
                ClientInfo.EQPInfo.LotList[0].LOSSINFOLIST = new List<Core.Entities.LOSSINFOLIST>();
                LossSN.LossInfoList = new List<Core.Entities.LOSSINFOLIST>();
                LossSN.count = 0;
                var strText = XfwUtils.Serialization(request.GetSerializationObject());
                context = XfwContext.GetMqContextByEAP(requestClient);
                var res = context.Request(strText);
                if (res != null)
                {
                    retMsg = res.GetReturnObject();
                }
                XfwContext.EapLogger.Information($"EAPClient.SendRemoveLot() Execute. ReturnCode: {retMsg.ReturnCode}, ReturnMessage: {retMsg.ReturnMessage}");
            }
            catch (Exception ex)
            {
                retMsg.SetReturnNG(ex.Message);
                XfwContext.EapLogger.Error(ex, $"EAPClient.SendRemoveLot() Execute Error.");
            }
            return retMsg;
        }
        public Return ChangeLanguage(string language)
        {
            EAPClient cq = new EAPClient();
           // requestClient = cq.Config.GetSection("RequestClient").Get<string>();
            string[] eqplst = cq.Config.GetSection("ToolIds").Get<string>().Split(',');
            List<string> EqpList = new List<string>();
            foreach (var item in eqplst)
            {
                EqpList.Add(item.Split('+')[0]);
            }
            var retMsg = new Return();
            try
            {
                    //foreach (var eqp in EqpList)
                    //{
                    //    if (item.Contains(eqp))
                    //    {
                    //        requestClient = item.Split('+')[1];
                    //        var request = new Request() { Header = XfwUtils.CreateHeader(MsgNameChangeLanguage, requestClient) };
                    //        request.Body.AddString(CItems.Language, language);
                    //        var strText = XfwUtils.Serialization(request.GetSerializationObject());
                    //        context = XfwContext.GetMqContextByEAP(requestClient);
                    //        var res = context.Request(strText);
                    //        if (res != null)
                    //        {
                    //            retMsg = res.GetReturnObject();
                    //        }
                    //        XfwContext.EapLogger.Information($"EAPClient.ChangeLanguage() Execute. ReturnCode: {retMsg.ReturnCode}, ReturnMessage: {retMsg.ReturnMessage}");
                    //    }
                    //}
                
            }
            catch (Exception ex)
            {
                retMsg.SetReturnNG(ex.Message);
                XfwContext.EapLogger.Error(ex, $"EAPClient.ChangeLanguage() Execute Error.");
            }
            return retMsg;
        }
        public Return Login(string username, string password, string facilityId)
        {
          
            var retMsg = new Return();
            try
            {               
                var request = new Request() { Header = XfwUtils.CreateHeader(MsgNameLogin, requestClient) };             
                request.Body.AddString(CItems.UserName, username);
                request.Body.AddString(CItems.Password, password);
                request.Body.AddString(CItems.FacilityId, facilityId);
                var strText = XfwUtils.Serialization(request.GetSerializationObject());
                context = XfwContext.GetMqContextByEAP(requestClient);
                var res = context.Request(strText);
                if (res != null)
                {
                    retMsg = res.GetReturnObject();
                }
                var messages = TranslateMsg.GetTranslation("LoginRequest");
                if (messages != null)
                {
                    ClientInfo.EQPInfo.LotList[0].ShowMsg(Core.Enums.MessageOrigin.EAP, Core.Enums.MessageType.Info, messages[RunService.Current.ClientLanguage]);
                    XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);
                }
                XfwContext.EapLogger.Information($"EAPClient.Login() Execute. ReturnCode: {retMsg.ReturnCode}, ReturnMessage: {retMsg.ReturnMessage}");
            }
            catch (Exception ex)
            {
                retMsg.SetReturnNG(ex.Message);
                XfwContext.EapLogger.Error(ex, $"EAPClient.Login() Execute Error.");
            }
            return retMsg;
        }
        /// <summary>
        /// 测试方法
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public Return GetCarrierLotInfo(object obj)
        {
            Dictionary<string, string> ss=obj as Dictionary<string, string>;
            EAPClient cq = new EAPClient();        
            var retMsg = new Return();
            try
            {
                var request = new Request() { Header = XfwUtils.CreateHeader(MsgNameGetCarrierLotInfo, requestClient) };                
                request.Body.AddString(CItems.LotID,ss["Lotid"]);
                request.Body.AddString(CItems.EqpID, ss["eqpname"]);
                request.Body.AddString(CItems.UserName, ss["UserId"]);
                request.Body.AddString(CItems.FacilityId, ss["facilityId"]);
                request.Body.AddString(CItems.ProberCardId, ss["proberCardId"]);
                request.Body.AddString(CItems.Alignment, ss["alignment"]);
                request.Body.AddString(CItems.TestMode, ss["testmode"]);
                request.Body.AddString(CItems.TestModeValue, ss["testsitemode"]); 
                var strText = XfwUtils.Serialization(request.GetSerializationObject());
                context = XfwContext.GetMqContextByEAP(requestClient);
                context.Configure.Timeout = 50000;
                Stopwatch sw = new Stopwatch();
                sw.Start();
                var res = context.Request(strText);
                sw.Stop();
                XfwContext.EapLogger.Debug($"调用{MsgNameGetCarrierLotInfo}接口，耗时为:{sw.ElapsedMilliseconds}");
                if (res != null)
                {
                    var aaa = res.GetVal<string>(CItems.UnitInfo);
                    retMsg.ReturnMessage = res.GetResponse().ToString();
                    //res.GetResponse
                }
                var messages = TranslateMsg.GetTranslation("LotInfoRequest");
                if (messages != null)
                {
                    ClientInfo.EQPInfo.LotList[0].ShowMsg(Core.Enums.MessageOrigin.EAP, Core.Enums.MessageType.Info, messages[RunService.Current.ClientLanguage]);
                    XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);
                }
                XfwContext.EapLogger.Information($"EAPClient.GetCarrierLotInfo() Execute. ReturnCode: {retMsg.ReturnCode}, ReturnMessage: {retMsg.ReturnMessage}");
            }
            catch (Exception ex)
            {
                retMsg.SetReturnNG(ex.Message);
                XfwContext.EapLogger.Error(ex, $"EAPClient.GetCarrierLotInfo() Execute Error.");
            }
            return retMsg;
        }


        public Return GetCarrierLotInfo(string lotId, string equipmentId, string userId, string facilityId,string proberCardId,string alignment,string testmode)
        {
            EAPClient cq = new EAPClient();
            //requestClient = cq.Config.GetSection("RequestClient").Get<string>();
            var retMsg = new Return();
            try
            {
                var request = new Request() { Header = XfwUtils.CreateHeader(MsgNameGetCarrierLotInfo, requestClient) };
                request.Body.AddString(CItems.LotID, lotId);
                request.Body.AddString(CItems.EqpID, equipmentId);
                request.Body.AddString(CItems.UserName, userId);
                request.Body.AddString(CItems.FacilityId, facilityId);
                request.Body.AddString(CItems.ProberCardId, proberCardId);
                request.Body.AddString(CItems.Alignment, alignment);
                request.Body.AddString(CItems.TestMode, testmode);
                var strText = XfwUtils.Serialization(request.GetSerializationObject());
               
              
               
                context = XfwContext.GetMqContextByEAP(requestClient);
               // context.Configure.Timeout = 50000;
                Stopwatch sw = new Stopwatch();
                sw.Start();
                
                
                var res = context.Request(strText);
                sw.Stop();
                XfwContext.EapLogger.Debug($"调用{MsgNameGetCarrierLotInfo}接口，耗时为:{sw.ElapsedMilliseconds}");
                if (res != null)
                {
                    var aaa = res.GetVal<string>(CItems.UnitInfo) ;
                    retMsg.ReturnMessage = res.GetResponse().ToString();          
                    //res.GetResponse
                }
                var messages= TranslateMsg.GetTranslation("LotInfoRequest");
                if (messages!=null)
                {
                    ClientInfo.EQPInfo.LotList[0].ShowMsg(Core.Enums.MessageOrigin.EAP, Core.Enums.MessageType.Info, messages[RunService.Current.ClientLanguage]);
                    XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);
                }
                XfwContext.EapLogger.Information($"EAPClient.GetCarrierLotInfo() Execute. ReturnCode: {retMsg.ReturnCode}, ReturnMessage: {retMsg.ReturnMessage}");
            }
            catch (Exception ex)
            {
                retMsg.SetReturnNG(ex.Message);
                XfwContext.EapLogger.Error(ex, $"EAPClient.GetCarrierLotInfo() Execute Error.");
            }
            return retMsg;
        }
        /// <summary>
        /// 开始online作业
        /// </summary>
        /// <param name="eqpId"></param>
        /// <returns></returns>
        public Return StartProgram(string testerid, string proberid)
        {
            EAPClient cq = new EAPClient();
            //requestClient = cq.Config.GetSection("RequestClient").Get<string>();
            var retMsg = new Return();
            try
            {
                var request = new Request() { Header = XfwUtils.CreateHeader(MsgNameStartProgram, requestClient) };
                request.Body.AddString(CItems.TesterID, testerid);
                request.Body.AddString(CItems.ProberID, proberid);
                var strText = XfwUtils.Serialization(request.GetSerializationObject());
                context = XfwContext.GetMqContextByEAP(requestClient);
                var res = context.Request(strText);
                if (res != null)
                {
                    retMsg = res.GetReturnObject();
                }
                XfwContext.EapLogger.Information($"EAPClient.StartProgram() Execute. ReturnCode: {retMsg.ReturnCode}, ReturnMessage: {retMsg.ReturnMessage}");
            }
            catch (Exception ex)
            {
                retMsg.SetReturnNG(ex.Message);
                XfwContext.EapLogger.Error(ex, $"EAPClient.StartProgram() Execute Error.");
            }
            return retMsg;
        }



        /// <summary>
        /// 暂停offline作业
        /// </summary>
        /// <param name="eqpId"></param>
        /// <returns></returns>
        public Return SendStopProcess(string testerid, string proberid)
        {
            EAPClient cq = new EAPClient();
           // requestClient = cq.Config.GetSection("RequestClient").Get<string>();
            var retMsg = new Return();
            try
            {
                var request = new Request() { Header = XfwUtils.CreateHeader(MsgNameSendStopProcess, requestClient) };
                request.Body.AddString(CItems.TesterID, testerid);
                request.Body.AddString(CItems.ProberID, proberid);
                var strText = XfwUtils.Serialization(request.GetSerializationObject());
                context = XfwContext.GetMqContextByEAP(requestClient);
                var res = context.Request(strText);
                if (res != null)
                {
                    retMsg = res.GetReturnObject();
                }
                XfwContext.EapLogger.Information($"EAPClient.StopProgram() Execute. ReturnCode: {retMsg.ReturnCode}, ReturnMessage: {retMsg.ReturnMessage}");
            }
            catch (Exception ex)
            {
                retMsg.SetReturnNG(ex.Message);
                XfwContext.EapLogger.Error(ex, $"EAPClient.StopProgram() Execute Error.");
            }
            return retMsg;
        }

        /// <summary>
        /// 人工手动出站
        /// </summary>
        /// <param name="eqpId"></param>
        /// <returns></returns>
        public Return TrackOutByUser(string eqpId, List<Core.Entities.LOSSINFOLIST> lossList)
        {
            EAPClient cq = new EAPClient();
          //  requestClient = cq.Config.GetSection("RequestClient").Get<string>();
            var retMsg = new Return();
            try
            {
                var request = new Request() { Header = XfwUtils.CreateHeader(MsgNameTrackOutByUser, requestClient) };

                request.Body.AddString(CItems.EqpID, eqpId);
                request.Body.AddList<Core.Entities.LOSSINFOLIST>(CItems.LossList, lossList);
                ClientInfo.EQPInfo.LotList[0].LOSSINFOLIST = new List<Core.Entities.LOSSINFOLIST>();
                LossSN.LossInfoList = new List<Core.Entities.LOSSINFOLIST>();
                LossSN.count = 0;
                var strText = XfwUtils.Serialization(request.GetSerializationObject());
                context = XfwContext.GetMqContextByEAP(requestClient);
                var res = context.Request(strText);
                if (res != null)
                {
                    retMsg = res.GetReturnObject();
                }
                XfwContext.EapLogger.Information($"EAPClient.TrackOutByUser() Execute. ReturnCode: {retMsg.ReturnCode}, ReturnMessage: {retMsg.ReturnMessage}");
            }
            catch (Exception ex)
            {
                retMsg.SetReturnNG(ex.Message);
                XfwContext.EapLogger.Error(ex, $"EAPClient.TrackOutByUser() Execute Error.");
            }
            return retMsg;
        }

        public Return TrackOutByOCR()
        {
            EAPClient cq = new EAPClient();
            //  requestClient = cq.Config.GetSection("RequestClient").Get<string>();
            var retMsg = new Return();
            try
            {
                var request = new Request() { Header = XfwUtils.CreateHeader(MsgNameTrackOutByOCR, requestClient) };
                var strText = XfwUtils.Serialization(request.GetSerializationObject());
                context = XfwContext.GetMqContextByEAP(requestClient);
                var res = context.Request(strText);
                if (res != null)
                {
                    retMsg = res.GetReturnObject();
                }
                XfwContext.EapLogger.Information($"EAPClient.TrackOutByocr() Execute. ReturnCode: {retMsg.ReturnCode}, ReturnMessage: {retMsg.ReturnMessage}");
            }
            catch (Exception ex)
            {
                retMsg.SetReturnNG(ex.Message);
                XfwContext.EapLogger.Error(ex, $"EAPClient.TrackOutByUser() Execute Error.");
            }
            return retMsg;
        }
        /// <summary>
        /// 发送心跳
        /// </summary>
        /// <param name="eqpId"></param>
        /// <returns></returns>
        public Return SendHeartBeat(string eqpId)
        {
            var retMsg = new Return();
            try
            {
                var request = new Request() { Header = XfwUtils.CreateHeader(HeartBeat, requestClient) };
                request.Body.AddString(CItems.EqpID, eqpId);
                var strText = XfwUtils.Serialization(request.GetSerializationObject());
                context = XfwContext.GetMqContextByEAP(requestClient);
               // context.Configure.Timeout = 50000;//心跳超时超时缩短
                var res = context.Request(strText);
                if (res != null)
                {
                    //retMsg.ReturnMessage = res.GetReturnMessage();
                    retMsg.ReturnCode = res.GetReturnCode();
                    retMsg.ReturnMessage = res.GetResponse().ToString();
                }
               // context.Configure.Timeout = 50000;
                XfwContext.EapLogger.Information($"EAPClient.SendHeartBeat() Execute. ReturnCode: {retMsg.ReturnCode}, ReturnMessage: {retMsg.ReturnMessage}");
            }
            catch (Exception ex)
            {
                retMsg.SetReturnNG(ex.Message);
                XfwContext.EapLogger.Error(ex, $"EAPClient.SendHeartBeat() Execute Error.");
               // context.Configure.Timeout = 50000;
            }

            return retMsg;
        }
        /// <summary>
        /// 筛选片
        /// </summary>
        /// <param name="eqpid"></param>
        /// <param name="waferid"></param>
        /// <param name="mesid"></param>
        /// <param name="">"IsFullmeasurement"</param>
        /// <returns></returns>
        public Return SelectWaferID(string eqpid, string waferid,string mesid,string IsFullmeasurement,string UnitidList,string TestMode)
        {
            var retMsg = new Return();
            try
            {
                var request = new Request() { Header = XfwUtils.CreateHeader(MsgNameSelectWaferID, requestClient) };
                request.Body.AddString(CItems.ProberID, eqpid);
                request.Body.AddString(CItems.SelectWaferID, waferid);
                request.Body.AddString(CItems.MesWaferID, mesid);
                request.Body.AddString(CItems.IsFullmeasurement, IsFullmeasurement);
                request.Body.AddString(CItems.UnitidList, UnitidList);
                request.Body.AddString(CItems.TestMode, TestMode);
                var strText = XfwUtils.Serialization(request.GetSerializationObject());
                context = XfwContext.GetMqContextByEAP(requestClient);
                var messages = TranslateMsg.GetTranslation("SelectWaferIDRequest");
                if (messages != null && messages.Count != 0)
                {
                    ClientInfo.EQPInfo.LotList[0].ShowMsg(Core.Enums.MessageOrigin.EAP, Core.Enums.MessageType.Info, messages[RunService.Current.ClientLanguage]);
                    XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);
                }
                var res = context.Request(strText);
                if (res != null)
                {
                    retMsg = res.GetReturnObject();
                }

                XfwContext.EapLogger.Information($"EAPClient.SelectWaferID() Execute. ReturnCode: {retMsg.ReturnCode}, ReturnMessage: {retMsg.ReturnMessage}");
            }
            catch (Exception ex)
            {
                retMsg.SetReturnNG(ex.Message);
                XfwContext.EapLogger.Error(ex, $"EAPClient.SelectWaferID() Execute Error.");
            }
            return retMsg;
        }
        /// <summary>
        /// 处理报警后，清除报警调整
        /// </summary>
        /// <param name="alarmid"></param>
        /// <returns></returns>
        public Return ClearAlarm(string alarmid)
        {
            EAPClient cq = new EAPClient();
            var retMsg = new Return();
            try
            {
                var request = new Request() { Header = XfwUtils.CreateHeader(MsgNameClearAlarm, requestClient) };
                request.Body.AddString(CItems.AlarmID, alarmid);          
                var strText = XfwUtils.Serialization(request.GetSerializationObject());
                context = XfwContext.GetMqContextByEAP(requestClient);
                var res = context.Request(strText);
                if (res != null)
                {
                    retMsg = res.GetReturnObject();
                }
                XfwContext.EapLogger.Information($"EAPClient.ClearAlarm() Execute. ReturnCode: {retMsg.ReturnCode}, ReturnMessage: {retMsg.ReturnMessage}");
            }
            catch (Exception ex)
            {
                retMsg.SetReturnNG(ex.Message);
                XfwContext.EapLogger.Error(ex, $"EAPClient.ClearAlarm() Execute Error.");
            }
            return retMsg;
        }

      
    }
}
